<template>
  <!-- 使用 flex 布局模式，设置屏幕长宽，背景颜色 -->
    <div class="screen" style="background: blanchedalmond">
        <el-row style="height: 100%; width: 100%" :justify="'center'" :align="'middle'">
            <el-button @click="auth_login" type="primary" round>OAuth登录</el-button>
        </el-row>
    </div>
</template>

<script setup>
import {onMounted} from "vue";
import {useRoute, useRouter} from "vue-router";
import {v4} from 'uuid'
import {sha256} from "js-sha256";
import axios from "axios";
import {PATH_URL, TOKEN_KEY} from "/@/assets/constant.js";
import {USER_INFO_KEY} from "../assets/constant.js";
import {CLIENT_ID, SCOPE} from "../assets/conf.js";

// 使用vue-router，vuex
const router = useRouter()
const route = useRoute()
// oauth登录的参数
const BASE_AUTH_URL = "http://localhost:8873"
const clientId = CLIENT_ID
const grantType = "authorization_code"
const redirectUri = "http://localhost:8873/admin/web/view/login"
const scope = SCOPE

/**
 * 登陆相关
 */

const auth_login = () => {
    window.open(BASE_AUTH_URL + "/oauth2/authorize?request_type=code&scope=" + scope + "&client_id=" + clientId + "&redirect_uri=" + redirectUri + "&code_challenge=" + rand_str() + "&code_challenge_method=S256")
}

// 使用auth的pk ce模式
const rand_str = () => {
    const uuid = v4()
    localStorage.setItem("code_verify", uuid)
    return sha256(uuid)
}

// 防止一直访问login页面
onMounted(() => {
    let token = localStorage.getItem(TOKEN_KEY)
    if (token !== null) {
        router.push(PATH_URL)
    }
    // 如果是授权回来的页面
    let code = route.query.code;
    if (code !== undefined) {
        // 开始授权
        let codeVerify = localStorage.getItem("code_verify")
        if (codeVerify !== undefined) {
            let from = new FormData()
            from.append("grant_type", grantType)
            from.append("client_id", clientId)
            from.append("redirect_uri", redirectUri)
            from.append("code", code)
            from.append("code_verifier", codeVerify)
            axios.post(BASE_AUTH_URL + "/oauth2/token", from).then(res => {
                if (res.data.token === "" || res.data.token === undefined) {
                    alert("登录失败")
                } else {
                    localStorage.setItem(TOKEN_KEY, res.data.token)
                    localStorage.removeItem("code_verify")
                    // 获取用户信息
                    axios.post(BASE_AUTH_URL + "/userinfo", undefined, {
                        headers: {
                            Authorization: `Bearer ` + res.data.token
                        }
                    }).then(res => {
                        let strUserData = JSON.stringify(res.data);
                        localStorage.setItem(USER_INFO_KEY, strUserData)
                    })
                    router.push(PATH_URL)
                }
            })
        } else {
            alert("异常的code_verify")
        }
    }
})
</script>

<style scoped>
</style>
